#! /usr/bin/env python

# NM64 class
#
# Copyright (C) 2011 Christian T. Steigies <steigies@physik.uni-kiel.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

__author__ = "Christian T. Steigies <steigies@physik.uni-kiel.de>"
__license__ = "GPL License"

## --------------------------------------------------------------------------
#import MySQLdb # python-mysqldb

import os
import sys

# http://docs.python.org/library/datetime.html
#from datetime import datetime, date, time, timedelta
import datetime

import calendar

from nmdb.tools.datetool import str2datetime

#from numpy import array

#http://docs.python.org/library/sqlite3.html
# SpaceWx uses CentOS5 with Python2.4 and pysqlite2
try:
    from pysqlite2 import dbapi2 as sqlite3
except ImportError:
    try:
        from sqlite3 import dbapi2 as sqlite3
    except ImportError:
        print "SQLite module not found"
        sys.exit(1)


#__all__ = ["", ""]

## --------------------------------------------------------------------------
class station(object):
    def __init__(self, name, year, month):

        self._this_station = name
        #self._station = []
        self._station = name
        self._data = []
        self._dict = {}
        self._year = year
        self._month = month

        self.__conn = sqlite3.connect(':memory:')
        #self.__conn = sqlite3.connect('test.sqlite')
        self._c = self.__conn.cursor()
        # Create table
        self._c.execute('''create table data (datetime timestamp, ucorr real, pressure real, corr real)''')
        self.__conn.commit()

    def station(self):
        return self._station

    def this_station(self):
        return self._this_station

    #def data(self, dt= datetime.datetime(1,1,1)):
    #    return self._data

    #def dict(self, dt= datetime.datetime(1,1,1)):
    #    return self._dict

    def _value(self, year=2000, month=1, day=1, hour=0, minute=0):
        """return values as read in"""
        
        data = [datetime.datetime(year, month, day, hour, minute, 0)]
        #print data
        self._c.execute('''SELECT datetime, ucorr, pressure, corr FROM data WHERE datetime == (?)''', data)
        row = self._c.fetchone() # should return only one line, or None
        #print "SQL:", row
        if row:
            (dt, u, p, c) = row
            utc = str2datetime(dt)
            #utc = datetime.datetime.strptime(dt, "%Y-%m-%d %H:%M:%S")
            return (utc, u, p, c)
            #return (utc, float(u), float(p), float(c))
        return None


    def min(self):
        self._c.execute('''SELECT MIN(datetime) FROM data''')
        [dt] = self._c.fetchone() # should return only one line, or None
        utc = str2datetime(dt)
        return utc

        
    def max(self):
        self._c.execute('''SELECT MAX(datetime) FROM data''')
        [dt] = self._c.fetchone() # should return only one line, or None
        utc = str2datetime(dt)
        return utc
        

    def sql(self, year=2000, month=1, day=1, hour=0, minute=0, limit=1):
        """return the value from internal SQL hour table which matches the given data"""
        data = [datetime.datetime(year, month, day, hour, minute, 0), limit]
        #print data
        self._c.execute('''SELECT datetime, ucorr, pressure, corr FROM data WHERE datetime >= (?) LIMIT (?)''', data)
        value = []
        for row in self._c:
            value.append(row)
        return value

## --------------------------------------------------------------------------
def CheckData(data, cr_min=1., cr_max=10000.):
    """check data for valid range, return as string"""

    if data == 0:
        #checked = "NULL"
        checked = None
    elif data < cr_min:
        print "Countrate: %f out of range (%f - %f)" %(data, cr_min, cr_max)
        #checked = "NULL"
        checked = None
        #raise ValueError #"countrate too low"
    elif data > cr_max:
        print "Countrate: %f out of range (%f - %f)" %(data, cr_min, cr_max)
        #checked = "NULL"
        #hecked = None
        #raise ValueError #"countrate too high"
    else:
        checked = data
        #checked = str("%.2f"%(data))

    return checked

## --------------------------------------------------------------------------
def CheckPressure(p, p_min=100., p_max=1500.):
    """check data for valid range, return as string"""

    if p == 0:
        #checked = "NULL"
        checked = None
    elif p < p_min:
        print "Pressure: %f out of range (%f - %f)" %(p, p_min, p_max)
        #checked = "NULL"
        checked = None
        #raise ValueError #"pressure too low"
    elif p > p_max:
        print "Pressure: %f out of range (%f - %f)" %(p, p_min, p_max)
        #checked = "NULL"
        checked = None
        #raise ValueError #"pressure too high"
    else:
        checked = p
        #checked = str("%.2f"%(p))

    return checked
## --------------------------------------------------------------------------

if __name__=="__main__":
    print "This is the NM64_class module."

